<template>
  <view class="login-container">
    <view class="login-form">
      <view class="logo-container">
        <image src="/static/logo.png" class="logo"></image>
        <view class="title">小富职说</view>
      </view>
      
      <view class="form-item">
        <view class="input-wrapper">
          <uni-icons type="person" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="text" v-model="loginForm.username" placeholder="请输入用户名" class="input" />
        </view>
      </view>
      
      <view class="form-item">
        <view class="input-wrapper">
          <uni-icons type="locked" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="password" v-model="loginForm.password" placeholder="请输入密码" class="input" />
        </view>
      </view>
      
      <view class="form-item" v-if="captchaEnabled">
        <view class="input-wrapper">
          <uni-icons type="text" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="text" v-model="loginForm.code" placeholder="请输入验证码" class="input" maxlength="4" />
          <!-- 验证码区域 - 显示验证码图片 -->
          <view class="login-code" @click="refreshCode">
            <image :src="codeUrl" class="login-code-img"></image>
          </view>
        </view>
      </view>
      
      <view class="remember-container">
        <uni-checkbox v-model="loginForm.rememberMe" class="remember-checkbox">
          <text class="remember-text">记住我</text>
        </uni-checkbox>
      </view>
      
      <button class="login-btn" @click="handleLogin" :loading="loading">登录</button>
      
      <view class="link-container">
        <text @click="goToRegister" class="link">立即注册</text>
        <text @click="goToReset" class="link">忘记密码</text>
      </view>
      
      <!-- 第三方登录 -->
      <view class="third-party-login">
        <view class="divider">
          <text class="divider-text">其他登录方式</text>
        </view>
        <view class="third-party-icons">
          <view class="icon-item" @click="socialLogin('weixin')">
            <uni-icons type="weixin" size="40" color="#07C160"></uni-icons>
            <text class="icon-text">微信</text>
          </view>
          <view class="icon-item" @click="socialLogin('qq')">
            <uni-icons type="qq" size="40" color="#12B7F5"></uni-icons>
            <text class="icon-text">QQ</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import request from '../../common/request'
import { login, getUserInfo, getCodeImg, socialCallback } from '@/api/user'

export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        code: '',
        rememberMe: false,
        clientId: 'web', // 客户端ID，与RuoYi后端配置一致
        grantType: 'password', // OAuth2授权类型
        uuid: '' // 验证码UUID
      },
      loading: false,
      codeUrl: '', // 验证码图片URL
      captchaEnabled: true // 验证码开关
    }
  },
  onLoad() {
    // 初始化时获取验证码
    this.refreshCode()
    // 获取本地存储的登录信息
    this.getLoginData()
  },
  methods: {
    // 刷新验证码
    async refreshCode() {
      try {
        console.log('开始获取验证码...')
        const res = await getCodeImg()
        console.log('验证码接口返回:', res)
        
        if (res.code === 200 && res.data) {
          // 检查是否启用验证码
          this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled
          if (this.captchaEnabled) {
            // 设置验证码图片URL
            this.codeUrl = `data:image/gif;base64,${res.data.img}`
            // 设置验证码UUID
            this.loginForm.uuid = res.data.uuid
  
          console.log('验证码UUID:', this.loginForm.uuid)
          }
          else {
          console.error('验证码接口返回异常:', res)
          // 错误情况下使用时间戳作为UUID
          this.loginForm.uuid = Date.now().toString();
        }
      }} catch (error) {
        console.error('获取验证码失败:', error)
        // 错误情况下使用时间戳作为UUID
        this.loginForm.uuid = Date.now().toString();
      }
      },
    
    // 获取本地存储的登录信息
    getLoginData() {
      const account = uni.getStorageSync('account')
      const password = uni.getStorageSync('password')
      const rememberMe = uni.getStorageSync('rememberMe')
      if (account) {
        this.loginForm.username = account
        if (password && rememberMe) {
          this.loginForm.password = password
          this.loginForm.rememberMe = Boolean(rememberMe)
        }
      }
    },
    
    // 表单验证
    validateForm() {
      if (!this.loginForm.username.trim()) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }
      if (!this.loginForm.password.trim()) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return false
      }
      if (this.captchaEnabled && !this.loginForm.code.trim()) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return false
      }
      return true
    },
    
    // 处理登录
    async handleLogin() {
      if (!this.validateForm()) {
        return
      }
      
      this.loading = true
      try {
        // 调用登录接口 - 符合RuoYi OAuth2流程
        console.log('提交登录数据:', {
          username: this.loginForm.username,
          password: '******', // 不打印密码
          code: this.loginForm.code,
          uuid: this.loginForm.uuid,
          clientId: this.loginForm.clientId,
          grantType: this.loginForm.grantType
        })
        
        // 确保以对象形式传递参数
        const res = await login({
          username: this.loginForm.username,
          password: this.loginForm.password,
          code: this.loginForm.code,
          uuid: this.loginForm.uuid
        })
        
        console.log('登录接口返回:', res)
        
        if (res.code === 200 && res.data) {
          // 保存token - 标准Bearer格式
          const token = res.data.token || res.data.access_token
          if (token) {
            uni.setStorageSync('Token', 'Bearer ' + token)
            // 如果选择记住我，保存用户名和密码
            if (this.loginForm.rememberMe) {
              uni.setStorageSync('account', this.loginForm.username)
              uni.setStorageSync('password', this.loginForm.password)
              uni.setStorageSync('rememberMe', 'true')
            } else {
              // 否则移除存储的信息
              uni.removeStorageSync('account')
              uni.removeStorageSync('password')
              uni.removeStorageSync('rememberMe')
            }
            console.log('用户登录成功')
            
            // 登录成功后获取用户信息 - 使用默认token机制
            const userInfoRes = await getUserInfo()
            console.log('获取用户信息返回:', userInfoRes)
            
            if (userInfoRes.code === 200 && userInfoRes.data) {
              // 保存用户信息
              uni.setStorageSync('UserInfo', userInfoRes.data)
              
              // 显示成功提示
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
              
              // 延迟后跳转到首页
              setTimeout(() => {
                // 先尝试返回上一页，如果没有上一页则跳转到首页
                const pages = getCurrentPages()
                if (pages.length > 1) {
                  uni.navigateBack()
                } else {
                  uni.switchTab({ url: '/pages/index/index' })
                }
              }, 1500)
            } else {
              throw new Error('获取用户信息失败')
            }
          }
        }
      } catch (error) {
        console.error('登录失败:', error)
        // 显示错误提示
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        })
        // 重新获取验证码
        if (this.captchaEnabled) {
          this.refreshCode()
        }
      } finally {
        this.loading = false
      }
    },
    
    // 跳转到注册页面
    goToRegister() {
      uni.navigateTo({
        url: '/pages/mine/register'
      })
    },
    
    // 跳转到重置密码页面
    goToReset() {
      uni.showToast({
        title: '重置密码功能暂未开放',
        icon: 'none'
      })
    },
    
    // 第三方登录
    socialLogin(type) {
      // 调用第三方登录回调接口
      socialCallback({ type }).then(res => {
        if (res.code === 200 && res.data) {
          // 重定向到授权地址
          window.location.href = res.data
        } else {
          uni.showToast({
            title: res.msg || '获取授权地址失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        console.error('第三方登录失败:', err)
        uni.showToast({
          title: '第三方登录失败',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
  padding: 40rpx 30rpx;
}

.login-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 60rpx;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #36D;
}

.form-item {
  width: 100%;
  margin-bottom: 24rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 0 30rpx;
  height: 96rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.input-icon {
  margin-right: 20rpx;
}

.input {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  color: #333;
}

.input::placeholder {
  color: #999;
}

/* 验证码图片样式 */
.login-code {
  width: 200rpx;
  height: 60rpx;
  cursor: pointer;
  margin-left: 20rpx;
}

.login-code-img {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

/* 记住我样式 */
.remember-container {
  width: 100%;
  margin-bottom: 30rpx;
}

.remember-checkbox {
  font-size: 28rpx;
  color: #666;
}

.remember-text {
  font-size: 28rpx;
  color: #666;
}

/* 按钮样式 */
.login-btn {
  width: 100%;
  height: 96rpx;
  background-color: #36D;
  color: #fff;
  font-size: 36rpx;
  border-radius: 8rpx;
  margin-bottom: 30rpx;
}

.login-btn:active {
  background-color: #25c;
}

/* 链接容器 */
.link-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 40rpx;
}

.link {
  font-size: 28rpx;
  color: #36D;
}

/* 第三方登录样式 */
.third-party-login {
  width: 100%;
  margin-top: auto;
  padding-bottom: 40rpx;
}

.divider {
  position: relative;
  height: 40rpx;
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.divider::before, .divider::after {
  content: '';
  flex: 1;
  height: 1rpx;
  background-color: #e0e0e0;
}

.divider-text {
  padding: 0 30rpx;
  font-size: 26rpx;
  color: #999;
}

.third-party-icons {
  display: flex;
  justify-content: center;
  gap: 60rpx;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.icon-text {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}
</style>